package com.example.easyexcel.exports.customized.util;


import cn.hutool.core.date.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

@Component
@Slf4j
public class ExportUtil implements ApplicationContextAware {

    private static String suffix =  ".xlsx";

    // 获取环境
    private static ApplicationContext applicationContext;
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        ExportUtil.applicationContext = applicationContext;
    }
    /**  */
    public static ApplicationContext getContext( ){
        return applicationContext ;
    }

    /**
     * 获取转义后的文件名
     */
    public static String createFileName(String name) throws UnsupportedEncodingException {
        String rawFileName = name + DateUtil.format(new Date(),"_yyyyMMdd_HHmmss") + suffix ;
        String encodedFileName = URLEncoder.encode(rawFileName, "UTF-8").replaceAll("\\+", "%20");
        return encodedFileName ;
    }


    /**
     * 设置excel下载的响应头属性
     */
    public static void setExcelRespProp(HttpServletResponse response, String fileName) {
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/octet-stream; charset=utf-8");

        response.setHeader("Content-Disposition", "attachment;filename=" + fileName );
        response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");

        response.setHeader("filename", fileName );
        response.setHeader("Access-Control-Expose-Headers", "filename");
    }

    /**
     * 返回行中 列的值及对应的位置
     * */
    public static Map<String,Integer> cellPosition(Row row){
        Map<String,Integer> map = new HashMap<>();
        Iterator<Cell> headerCells = row.iterator() ;
        while (headerCells.hasNext()){
            Cell cell = headerCells.next();
            map.put( cell.getStringCellValue() , cell.getColumnIndex() ) ;
        }
        return map ;
    }



}